<?php

namespace app\nideshop\controller;

use app\nideshop\service\Weixin;
use app\nideshop\service\Token;
use think\Db;


class Auth extends Base
{
    protected $datas;

    /**
     * 微信登录
     */
    public function loginByWeixinAction()
    {
        $this->datas = $this->params;
        $clientIp = request()->ip();
        $code = $this->datas['code'];
        $userInfo = $this->datas['userInfo'];
        $weixinRes = Weixin::login($code, $userInfo);
        // 此时登录鉴权失败
        if ($weixinRes['errno'] != 0)
        {
            return json($weixinRes);
        }
        
        // 先查下用户是否存在
        $openid = $weixinRes['data']['sessionData']['openid'];
        $userInfo = $weixinRes['data']['userInfo'];
        $userId = Db::name('user')
        ->where('weixin_openid', $openid)
        ->field('id')
        ->value('id');

        $username = substr(md5(time()), 0, 6);
        // 过滤特殊字符
        $nickName = preg_replace('/[\x{10000}-\x{10FFFF}]/u', '',  $userInfo['nickName']);
        // 新增一个用户
        if (empty($userId))
        {
            $userId = Db::name('user')
            ->insertGetId([
                'username' => '微信用户'.$username,
                'password' => '',
                'register_time' => time(),
                'register_ip' => $clientIp,
                'mobile' => '',
                'weixin_openid' => $openid,
                'avatar' =>  $userInfo['avatarUrl'],
                'gender' => $userInfo['gender'],
                'nickname' => $nickName
            ]);
        }

        // 查询用户信息
        $newUserInfo = Db::name('user')
        ->field('id,username,nickname,gender,avatar,birthday')
        ->where('id', $userId)
        ->find();

        Db::name('user')
        ->where('id', $userId)
        ->update([
            'last_login_time' => time(),
            'last_login_ip' => $clientIp
        ]);

        return json([
            'errno' => 0,
            'errmsg' => '成功',
            'data' => [
                'token' => Token::lock_url($userId),
                'userInfo' => $newUserInfo
            ]
        ]);
    }

    public function logoutAction()
    {
        return json([
            'errno' => 0,
            'errmsg' => '成功'
        ]);
    }
}
